from pydantic import BaseModel,field_serializer, ConfigDict, Field,Extra
from datetime import datetime
from typing import Optional, Dict, Any
import json


class CommentBase(BaseModel):
    content: str = Field(default='', description="内容")
    username: str = Field(default='', description="用户名称")

class CommentCreate(CommentBase):
    type:Optional[str]= ''
    created_at: Optional[datetime] = None
    user_id:Optional[int]= None
    status: Optional[str] = Field(default='approved', description="状态")
    extradata: Optional[Dict[str, Any]] = Field(default=None, description="扩展字段")

    class Config:
        from_attributes = True

class ItemComment(CommentBase):
    id: int
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    deleted_at: Optional[datetime] = None
    status: Optional[str] = None
    extradata: Optional[Dict[str, Any]] = None
    parent_id: Optional[int] = None
    post_id: Optional[int] = None
    user_id: Optional[int] = None
    type: Optional[str] = Field(default='', description="标签类型")

    # model_config = ConfigDict(from_attributes=True)
    @field_serializer("extradata")
    def serialize_metadata(self, value: Any) -> Optional[Dict[str, Any]]:
        if value is None:
            return None
        if isinstance(value, dict):
            return value
        try:
            return json.loads(str(value))  # 尝试解析字符串
        except json.JSONDecodeError:
            return {"raw_data": str(value)}  # 兜底逻辑
    # # orm_model=True 允许ORM模型转换
    model_config = ConfigDict(from_attributes=True,orm_model=True)

class ListComment(CommentBase):
    type: Optional[str] = Field(default='', description="标签类型")  # 非必填参数
    created_at: Optional[datetime] = None  # 非必填参数
    pageIndex: int = 1
    pageSize: int = 10

    class Config:
        # orm_mode = True
        from_attributes = True

class findComment(BaseModel):
    id: int = Field(..., description="id")

    class Config:
        from_attributes = True